<?php

/**
 * 排期控制器
 *
 * @author mengyuwang
 */

require_once 'CommonController.php';

class Admin_SourceSchedualController extends Admin_CommonController
{
    /**
     * 初始化函数
     * 
     * @return void
     */
    public function init()
    {
        parent::init();
        $this->_model = new Application_Model_SourceSchedual();
        $this->_productModel = new Application_Model_PartnerProduct();   
        $this->_sourceModel = new Application_Model_Source();     
        $this->_sourceAppModel = new Application_Model_SourceApp();
        $this->_dayDataModel = new Application_Model_DayData();
        $this->view->title = "管理中心";
    }

    /**
     * 列出指定sourceId和ProductCode,year,month的所有排期数据
     * 
     * @return void
     */
    public function indexAction()
    {           
        $row['sourceId'] = $this->view->sourceId=$sourceId = trim($this->_request->get('sourceId'));
        $row['sourceSubId'] = $this->view->sourceSubId=$sourceId = trim($this->_request->get('sourceSubId'));
        $row['productCode'] = $productCode = $this->view->currentProductCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $this->view->year = $row['year']=$year = $this->_request->getPost('year')?$this->_request->getPost('year'):date('Y');
        $this->view->month = $row['month']=$month = $this->_request->getPost('month')?$this->_request->getPost('month'):date('n');
        $this->view->weekday = date('w',strtotime($row['year'].'-'.$row['month'].'-1 0:0:0'));
        
        if ($this->view->weekday == 5 || $this->view->weekday == 6 ) {
            $this->view->line = 6;
        } else {
            $this->view->line = 5;
        }
        
        $this->view->pageUrl = $this->view->projectUrl($row);
        
        if (in_array($month, array('1', '3', '', '5', '7', '8', '10', '12'))) {
            $day = 31;
        } else if ($month == 2) {
            if ($year % 4 == 0 && $year % 100 != 0) {
                $day = 29;
            } else {
                $day = 28;
            }
        } else {
            $day = 30;
        }
        
        $this->view->day=$day;        
        $this->view->model=$this->_model;
        $this->view->dateRow=$row;
    }    
   
    /**
     * 添加动作
     * 
     * @return void
     */
    public function insertAction()
    {
        $this->view->partners = $this->_productModel->fetchAll();
        $currentProductCode = $this->view->currentProductCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $currentProduct = $this->_productModel->fetchRow("code = '{$currentProductCode}'");
        $this->view->sources = $this->_sourceModel->fetchAll("`productCode`='{$currentProductCode}'");
        $this->view->sourceId = $sourceId = $this->_request->get('sourceId');
        $this->view->sourceSubId = $sourceSubId = $this->_request->get('sourceSubId');
        $this->view->currentProductName = $currentProduct['name'];
        if ($this->_request->isPost()) {
            $filter = new Zend_Filter_StripTags();
            $startTime = $filter->filter(trim($this->_request->getPost('startTime')));
            $endTime = $filter->filter(trim($this->_request->getPost('endTime')));
            $row = array();           
            $row['productCode'] = $filter->filter(trim($this->_request->getPost('productCode')));
            $row['sourceId'] = $filter->filter(trim($this->_request->getPost('sourceId')));
            $row['sourceSubId'] = $filter->filter(trim($this->_request->getPost('sourceSubId')));
            $row['addTime']  = date('Y-m-d H:i:s');
            $row['paymentMethod'] =  $filter->filter(trim($this->_request->getPost('paymentMethod')));
            $row['price'] = floatval($this->_request->getPost('price'));
            $row['addUserName'] = $this->_currentUserRow['userName'];            
            if (strlen($row['productCode']) < 0) {
                echo $this->view->message('必须选择商家，请重新填写！') ;
                exit;
             }
             
            if (strlen($row['sourceId']) < 0) {
                echo $this->view->message('必须填写sourceId，请重新填写！') ;
                exit;
             }

            if (strlen($row['sourceSubId']) < 0) {
                echo $this->view->message('必须填写sourceSubId，请重新填写！') ;
                exit;
             }

           if (strlen($row['paymentMethod']) < 0) {
                echo $this->view->message('必须选择支付类型，请重新填写！') ;
                exit;
            }
            
            $row['price'] = abs(floatval($row['price']));
            $row['cpaPrice'] = $row['price'];
            
            if ($startTime && $endTime) {
                //获取天数
                $d1=strtotime($startTime);
                $d2=strtotime($endTime);
                $days=round(($d2-$d1)/3600/24);
                if($days<0){
                    echo $this->view->message('开始时间和结束时间不能颠倒，请重新填写！') ;
                    exit;
                }
                $d1arr=explode('-', $startTime);
                $m=$d1arr[1];
                $y=$d1arr[0];
                $d=$d1arr[2];
                $installNum = 0;
                
                for($i=0; $i<=$days; ++$i) {
                    if ($i == 1){
                        
                        $row['date']=date('Y-m-d',strtotime("+$i day",mktime(0,0,0,$m,$d,$y)));    
                       
                    } else {
                        $row['date']=date('Y-m-d',strtotime("+$i days",mktime(0,0,0,$m,$d,$y)));    
                        
                    }
                    if ($this->_model->existsRow($row)) {
                        //在这段时间内已经有记录，不可以插入
                        echo $this->view->message('在这段时间内已经有记录，请重新填写！') ;
                        exit;                       
                    } 
                    
                     //执行插入
                     for ($i=0; $i<=$days; ++$i) {
                         if ($i == 1) {
                               $row['date']=date('Y-m-d',strtotime("+$i day",mktime(0,0,0,$m,$d,$y)));    
                         } else {
                               $row['date']=date('Y-m-d',strtotime("+$i days",mktime(0,0,0,$m,$d,$y)));    
                         }
                         if ($row['paymentMethod'] == 'CPA') {                            
                                $dayData = $this->_dayDataModel->fetchAll("productCode='{$row['productCode']}' and sourceId='{$row['sourceId']}' 
                                and sourceSubId='{$row['sourceSubId']}' and date='{$row['date']}'");
                                $installNum = 0;
                                foreach ($dayData as $install) {
                                    $installNum += $install['installNum'];                    
                                }
                                $row['price'] = $row['price'] * $installNum;                                
                         }
                         $this->_model->insert($row);
                         
                     }   
                }
                
            } else {
                echo $this->view->message('开始时间和结束时间不能为空，请重新填写！') ;
                exit;
            }
            echo $this->view->message('操作成功！', $this->view->projectUrl(array('action' => 'list','controller'=>'source'))) ;
            exit;
        }
    }
   
    /**
     * 删除动作
     * 
     * @return void
     */
    public function deleteAction()
    {
        if ($this->_request->isPost()) {
            $ids= $this->_request->getPost('selectId');
            
            if (is_array($ids)) {
                
                foreach ($ids as $id) {
                   $source=$this->_model->fetchRow("id={$id}");
                   $sourceId=$source['sourceId'];
                   $sourceSubId = $source['sourceSubId'];
                }
                 $this->_model->deleteByIds($ids);
            }
        }
      redirect($this->view->projectUrl(array('action'=>'index','sourceId'=>$sourceId,'sourceSubId'=>$sourceSubId)));
    }
    
    /**
     * 导入列表
     * @return void
     */
    public function importAction(){
        $rows = array();

        if ($this->_request->isPost()) {
            if (!is_uploaded_file($_FILES['uploadfile']['tmp_name'])) {
                echo $this->view->message('上传错误！') ;
                exit;
            }
            if ($_FILES["uploadfile"]["size"] > 10000000) { //1M
                echo $this->view->message('上传文件不能大于1MB！') ;
                exit;
            }
            $ext = strtolower(substr($_FILES['uploadfile']['name'], strrpos($_FILES['uploadfile']['name'], '.') + 1));
            if (!($ext == 'xls' || $ext == 'xlsx')) {              
                echo $this->view->message('你只能上传XLS、XLSX格式文件！') ;
                exit;
            }
            $path = PUBLIC_PATH . "/data/sourceSchedual";
            createDirectory($path);
            $fileName = date("YmdHis") . ".{$ext}";
            copy($_FILES["uploadfile"]["tmp_name"], $path . "/" . $fileName);
            $objPHPExcel = PHPExcel_IOFactory::load($path . "/{$fileName}");
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
            $successNum = 0;

            $time = time();
            $n = 0;
            $updateNum = 0;
            $insertNum = 0;
            $errorNum = 0;
            $installNum = 0;
            @unlink($path . "/" . $fileName);
            for ($i = 2; $i <= $highestRow; $i++) {
                $n++;
                $row['productCode'] = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
                $row['sourceId'] = trim($objWorksheet->getCellByColumnAndRow(0, $i)->getValue());
                $row['sourceSubId'] = trim($objWorksheet->getCellByColumnAndRow(1, $i)->getValue());
                $row['date'] = trim($objWorksheet->getCellByColumnAndRow(2, $i)->getValue());
                $row['date'] = date('Y-m-d',strtotime(excelTime($row['date'])));
                $row['paymentMethod'] = trim($objWorksheet->getCellByColumnAndRow(3, $i)->getValue());
                $row['price'] = abs(floatval($objWorksheet->getCellByColumnAndRow(4, $i)->getValue()));
                $row['addTime'] = date('Y-m-d H:i:s');

                $lineMsg = "产品编号：“{$row['productCode']}”， SourceId:“{$row['sourceId']}”，SourceSubId:“{$row['sourceSubId']}”，日期：“{$row['date']}” ";

                if ($row['sourceId'] == '') {
                    echo ("第{$n}条，导入失败，sourceId空。<br/><br/>\r\n\r\n");
                    $errorNum++;
                } else if ($row['sourceSubId'] == '') {
                    echo ("第{$n}条，导入失败，sourceSubId为空。<br/><br/>\r\n\r\n");
                    $errorNum++;
                } else if (!$this->_sourceModel->existsSource($row['sourceId'], $row['sourceSubId'], $row['productCode'])) {
                    echo ("第{$n}条，{$lineMsg}，导入失败，sourceId，sourceSubId不存在。<br/><br/>\r\n\r\n");
                    $errorNum++;
                } else if ($row['date'] == '') {
                    echo ("第{$n}条，导入失败，日期空。<br/><br/>\r\n\r\n");
                    $errorNum++;
                } else {
                    //CPA价格处理
                    if (strtoupper($row['paymentMethod']) == 'CPA') {
                        $dayData = $this->_dayDataModel->fetchAll("productCode='{$row['productCode']}' and sourceId='{$row['sourceId']}' 
                         and sourceSubId='{$row['sourceSubId']}' and date='{$row['date']}'");
                        $installNum = 0;
                         foreach ($dayData as $install) {
                             $installNum += $install['installNum'];                    
                         }
                        $row['cpaPrice'] = $row['price'];
                        //检查装机数是否存在
                        if (!empty($installNum)) {
                            $row['price'] = $row['price'] * $installNum;
                        } else {
                            $row['price'] = 0;
                        }
                    }  
                    if ($this->_model->existsRow($row)) {
                        //覆盖数据库里的这条记录
                        $this->_model->updateRow($row);
                        $updateNum++;
                        echo ("第{$n}条，{$lineMsg}更新成功！<br/><br/>\r\n\r\n");
                    } else {
                        if ($row['paymentMethod'] == '') {
                            $row['paymentMethod'] = '其他';
                        }
                        $this->_model->insert($row);
                        $insertNum++;
                        echo ("第{$n}条，{$lineMsg}新增成功！<br/><br/>\r\n\r\n");
                    }
                }
            }
            echo "共导入{$n}条记录，其中新增{$insertNum}条，更新{$updateNum}条，错误{$errorNum}条。<script>setTimeout(function(){location.href='{$this->view->projectUrl()}';}, 10000);</script>";
            exit;
        }
        
    }
}